<!--
 * @Author: zqg
 * @Date: 2021-01-10 15:51:10
 * @LastEditors: zqg
 * @LastEditTime: 2021-03-20 19:10:18
 * @Description: file content
-->
<template>
  <base-layout
    :visible-sea="false"
    :visible-content="false"
    :dialog-title="title"
    :dialog-visible="dialogVisible"
    @dialog-close="handleClose"
    dialogWidth="60%"
  >
    <template #dialog>
      <el-form
        label-width="130px"
        v-if="!currentAddTypeInfo"
      >
        <el-row>
          <el-col>{{ title }}</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row
          v-for="(item, index) in types['考勤分类'].length / 3"
          :key="index"
        >
          <el-col
            class="add-btns"
            :span="8"
            v-for="item in types['考勤分类'].slice(index * 3, (index + 1) * 3)"
            :key="item.type"
          >
            <el-button @click="chooseType(item)">{{ item.text }}</el-button>
          </el-col>
        </el-row>
      </el-form>

      <el-form
        :model="addAttendanceBase"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        v-else
      >
        <el-row>
          <el-col>{{ title }}</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-form-item
          v-show="fromConfig.holidayType.isShow"
          :label="fromConfig.holidayType.labalText + ':'"
          prop="holidayType"
        >
          <el-select
            v-model="addAttendanceBase.holidayType"
            placeholder="请选择假期类型"
          >
            <el-option
              v-for="holidayItem in holidayTypeOption"
              :key="holidayItem.id"
              :label="holidayItem.dictValue"
              :value="holidayItem.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item
              :label="currentAddTypeInfo.text + '员工:'"
              prop="employees"
            >
              <user-select
                v-model="addAttendanceBase.employees"
                :store-id="currentStoreId"
                @change="selectUser"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-col :span="12">
          <el-form-item
            label="员工电话:"
            prop="position"
          >
            <el-input
              :value="userInfo.phone || ''"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="员工职位:"
            prop="position"
          >
            <el-input
              :value="userInfo.roleNames || ''"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item
              v-show="fromConfig.beginTime.isShow"
              :label="fromConfig.beginTime.labalText + ':'"
              prop="beginTime"
            >
              <el-date-picker
                type="datetime"
                value-format="yyyy-MM-dd hh:mm:ss"
                placeholder="选择日期"
                v-model="addAttendanceBase.beginTime"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-show="fromConfig.endTime.isShow"
              :label="fromConfig.endTime.labalText + ':'"
              prop="endTime"
            >
              <el-date-picker
                type="datetime"
                value-format="yyyy-MM-dd hh:mm:ss"
                placeholder="选择日期"
                v-model="addAttendanceBase.endTime"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label-width="0">
          <el-col :span="12">
            <el-form-item
              v-show="fromConfig.howLong.isShow"
              :label="fromConfig.howLong.labalText + ':'"
              prop="howLong"
            >
              <el-input v-model="addAttendanceBase.howLong"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item
          label="备注:"
          prop="remark"
        >
          <el-input
            type="textarea"
            clearable
            v-model="addAttendanceBase.remark"
          />
        </el-form-item>
      </el-form>
      <div
        class="footer"
        v-show="currentAddTypeInfo"
      >
        <el-button
          type="primary"
          @click="save"
        >保存</el-button>
      </div>
    </template>
  </base-layout>
</template>

<script>
import BaseLayout from '@/views/layout/Base'
import { getDict } from '@/utils/index'
import { getUserId } from '@/api/after-sale/personnel/index'
import { createAttendance } from '@/api/after-sale/personnel/attendance'
import { dictPage } from '@/api/after-sale/dictionary'
import UserSelect from '@/components/CommonForm/UserSelect'
import { addAttendanceFromConfig } from '@/utils/attendance'
export default {
  components: { BaseLayout, UserSelect },
  data() {
    return {
      currentStoreId: '',
      dialogVisible: false,
      // 保存成功回调
      saveSuccess: null,
      // 考勤类型列表
      types: getDict(['考勤分类']),
      // 当前选择的新增考勤类型信息
      currentAddTypeInfo: null,
      // 假期类型下拉列表
      holidayTypeOption: [],
      // 新增考勤基本信息字段
      addAttendanceBase: {
        // 假期类型（请假使用）
        holidayType: '',
        // 员工
        employees: '',
        // 只有一个时间时，使用改字段
        beginTime: '',
        endTime: '',
        // 时长
        howLong: '',
        remark: ''
      },
      userInfo: {},
      // 员工列表
      employeesOption: []
    }
  },
  computed: {
    // 弹窗标题
    title() {
      return this.currentAddTypeInfo
        ? '新增' + this.currentAddTypeInfo.text
        : '添加考勤类型'
    },
    // 表单显示配置
    fromConfig() {
      return addAttendanceFromConfig(this.currentAddTypeInfo.type)
    },
    // 表单验证规则
    rules() {
      return {
        holidayType: [
          {
            required: this.fromConfig.holidayType.isShow,
            message: '请选择'
          }
        ],
        employees: [
          {
            required: true,
            message: '请输入'
          }
        ],
        beginTime: [
          {
            required: true,
            message: '请输入'
          }
        ],
        endTime: [
          {
            required: this.fromConfig.endTime.isShow,
            message: '请输入'
          }
        ],
        howLong: [
          {
            required: this.fromConfig.howLong.isShow,
            message: '请输入'
          }
        ]
      }
    }
  },
  methods: {
    /**
     * @description: 打开弹窗
     * @param {Function}
     * @return {void}
     */
    async open(currentUserId, callback = () => { }) {
      this.dialogVisible = true
      this.currentAddTypeInfo = null
      this.saveSuccess = callback
      await this.getUserInfo(currentUserId)
      await this.getHolidayList()
    },
    /**
     * @description: 关闭弹窗
     * @param {*}
     * @return {*}
     */
    handleClose() {
      this.dialogVisible = false
      this.addAttendanceBase = {
        holidayType: '',
        employees: '',
        beginTime: '',
        endTime: '',
        howLong: '',
        remark: ''
      }
      this.userInfo = {}
    },
    /**
     * @description: 选择考勤类型
     * @param {Object} type
     * @return {*}
     */
    chooseType(info) {
      this.currentAddTypeInfo = info
    },
    /**
     * @description: 选择员工回调
     * @param {Object} 员工信息
     * @return {*}
     */
    selectUser(row) {
      getUserId(row.id).then(res => {
        this.userInfo = res.data || {}
      })
    },
    /**
     * @description: 获取新增考勤请求的参数
     * @param {*}
     * @return {*}
     */
    getRequestParam() {
      const addAttendanceBase = this.addAttendanceBase
      const query = {
        userId: addAttendanceBase.employees,
        // 考勤类型
        attendanceType: this.currentAddTypeInfo.value,
        // 天数
        dayNum: addAttendanceBase.howLong,
        // 开始时间
        startTime: addAttendanceBase.beginTime,
        // 结束时间(对于只存在一个时间的开始时间和结束时间一样)
        endTime: addAttendanceBase.endTime
          ? addAttendanceBase.endTime
          : addAttendanceBase.beginTime,
        // 假期类型(字典)–新增不传
        holidayDictValue: '',
        remark: addAttendanceBase.remark
      }
      // 假期类型(字典)–请假才存在
      if (addAttendanceBase.holidayType) {
        query.holidayDictId = addAttendanceBase.holidayType
      }
      return query
    },
    /**
     * @description: 保存
     * @param {*}
     * @return {*}
     */
    save() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          createAttendance(this.getRequestParam()).then(res => {
            let { success } = res
            if (success) {
              this.$message.success('保存成功')
              this.saveSuccess()
              this.handleClose()
            }
          })
        }
      })
    },
    /**
     * @description: 获取用户信息
     * @param {String ｜ Number} 用户id
     * @return {Promise}
     */
    getUserInfo(id = '') {
      return getUserId(id).then(res => {
        this.currentStoreId = res.data.storeId
      })
    },
    /**
     * @description: 获取假期类型列表
     * @param {*}
     * @return {Promise}
     */
    getHolidayList() {
      return dictPage(
        {
          storeId: null,
          dictValue: null,
          dictKey: '假期类型'
        },
        100,
        1
      ).then(({ success, data }) => {
        if (success) {
          this.holidayTypeOption = data.content || []
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 0;
}
.add-btns {
  text-align: center;
  margin-bottom: 20px;
  .el-button--medium {
    width: 146px;
    height: 42px;
    padding: 0;
  }
}
.footer {
  text-align: center;
}
</style>
